﻿using Data.Comic;
using Data.Facebook;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Net;
using System.Web;
using System.Web.Mvc;

namespace Index.Controllers
{
    public class ComicController : Controller
    {
        string domain = "http://truyen.kiso.vn";
        private ComicEntities db = new ComicEntities();
        ComicRepos _ComicRepos = new ComicRepos();
        public ActionResult Index(string type, string chars, string genre, int? p)
        {

            if (chars == "" || chars == null || chars == "tat-ca")
            {
                ViewBag.chars = "/by-tat-ca";
                chars = "%";
            }
            else
            {
                ViewBag.chars = "/by-" + chars;
            }


            if (type == "" || type == null)
            {
                type = "ten-truyen";
            }
            ViewBag.type = "/sx-" + type;
            int types = 0;
            if (type == "ten-truyen")
            {
                types = 1;
            }
            if (type == "ten-truyen-z-a")
            {
                types = 11;
            }
            if (type == "so-chuong")
            {
                types = 22;
            }
            if (type == "so-chuong-tang-dan")
            {
                types = 2;
            }

            if (type == "luot-xem")
            {
                types = 33;
            }
            if (type == "luot-xem-tang-dan")
            {
                types = 3;
            }
            if (type == "binh-luan")
            {
                types = 44;
            }
            if (type == "binh-luan-tang-dan")
            {
                types = 4;
            }
            List<GetComicByChar_Result> lsts = new List<GetComicByChar_Result>();
            if (string.IsNullOrEmpty(genre))
            {
                lsts = db.GetComicByChar(chars + "%", types, 24, 1).ToList();

            }
            else
            {
                ViewBag.Gender = "/loai-truyen-" + genre;
                List<GetTheLoai_Result> lst2 = db.GetTheLoai(genre, chars + "%", types, 24, 1).ToList();
                lsts = getGenner(lst2);
            }
            return View(lsts);

        }
        public PartialViewResult ListView(IEnumerable<GetComicByChar_Result> listComic)
        {
            return PartialView(listComic);
        }
        public PartialViewResult ListView1(IEnumerable<GetComicByChar_Result> listComic)
        {
            return PartialView(listComic);
        }
        public PartialViewResult ListView2(IEnumerable<Comic> listComic)
        {
            return PartialView(listComic);
        }
        public CommentModel GetListComent(string comments_fbid, string limit, string before, string after)
        {
            string ApiUrl = "https://graph.facebook.com/" + comments_fbid + "/comments?limit=" + limit;
            if (before.Length > 3)
            {
                ApiUrl += "&before=" + before;
            }
            if (after.Length > 3)
            {
                ApiUrl += "&after=" + after;
            }
            string json = DownloadHtml(ApiUrl);
            CommentModel cm = JsonConvert.DeserializeObject<CommentModel>(json);
            return cm;
        }
        public Datas GetFaceModel(string url)
        {
            string ApiUrl = "https://graph.facebook.com/fql?q=SELECT url, normalized_url, share_count, like_count, comment_count, total_count, commentsbox_count, comments_fbid, click_count FROM link_stat WHERE url =\"" + url + "\"";
            string json = DownloadHtml(ApiUrl);
            FaceModel fm = JsonConvert.DeserializeObject<FaceModel>(json);
            Datas df = fm.data.FirstOrDefault();
            return df;
        }
        public string DownloadHtml(string url)
        {
            try
            {
                WebClient client = new WebClient();
                client.Headers.Add("user-agent", "Mozilla/5.0 (iPhone; U; CPU iPhone OS 4_3_2 like Mac OS X; en-us) AppleWebKit/533.17.9 (KHTML, like Gecko) Version/5.0.2 Mobile/8H7 Safari/6533.18.5");
                client.Headers.Add("Accept-Encoding", "");
                return client.DownloadString(url);
            }
            catch (Exception ex)
            {
                return ex.Message;
            }
        }

        public ActionResult View(string slug)
        {
            ViewBag.domain = domain;
            Comic Comic = _ComicRepos.Get(slug);
            if (Comic != null)
            {
                Datas data = GetFaceModel(domain + "/truyen-tranh-" + Comic.Slug);
                Comic.CommentCount = data.comment_count;
                Comic.Like = data.like_count;
                if (Comic.Views == null)
                {
                    Comic.Views = 1;
                }
                else
                {
                    Comic.Views = Comic.Views + 1;
                }
                var objt = db.ComicGenre.Where(e => e.ComicId == Comic.Id).ToList();
                foreach (var item in objt)
                {
                    var obj = db.Genre.Where(e => e.Id == item.GenreId).FirstOrDefault();
                    if (obj.Views == null)
                    {
                        obj.Views = 1;
                    }
                    else
                    {
                        obj.Views = obj.Views + 1;
                    }
                    db.Entry(obj).State = EntityState.Modified;
                }

                db.Entry(Comic).State = EntityState.Modified;
                db.SaveChanges();
            }

            IEnumerable<Chapter> listChapter = _ComicRepos.ListChapter(Comic.Id);
            IEnumerable<ComicGenre> lstComicGenre = _ComicRepos.ListComicGenre(Comic.Id);
            ComicView ComicView = new ComicView
            {
                comic = Comic,
                listChapter = listChapter,
                TotalChapter = listChapter.Count(),
                ListComicGenre = lstComicGenre
            };

            return View(ComicView);
        }
        public ActionResult Chapter(string slug, int Id)
        {
            Comic Comic = _ComicRepos.Get(slug);
            IEnumerable<Chapter> listChapter = _ComicRepos.ListChapter(Comic.Id);
            Chapter chapter = listChapter.Where(x => x.Index == Id).FirstOrDefault();
            IEnumerable<Pages> listPage = _ComicRepos.ListPage(chapter.Id);
            if (listPage.Count() > 0)
            {
                ViewBag.Image = listPage.ElementAt(0).Url.Split('/');
            }

            ChapterView chapterView = new ChapterView
            {
                comic = Comic,
                chapter = chapter,
                listPage = listPage,
                listChapter = listChapter,
                TotalChapter = listChapter.Count(),
                TotalPage = listPage.Count()
            };
            return View(chapterView);
        }
        public PartialViewResult ListGenre(string type, string chars, string genre)
        {
            ViewBag.type = type;
            ViewBag.chars = chars;
            ViewBag.Gender = genre;
            return PartialView(_ComicRepos.ListGenre());

        }
        public PartialViewResult Tops()
        {
            var lst = db.Genre.OrderByDescending(e => e.Views).Take(3).ToList();
            ViewBag.lst1 = db.GetTheLoai(lst.ElementAt(0).Slug, "%%", 33, 10, 1).ToList();
            ViewBag.lst2 = db.GetTheLoai(lst.ElementAt(1).Slug, "%%", 33, 10, 1).ToList();
            ViewBag.lst3 = db.GetTheLoai(lst.ElementAt(2).Slug, "%%", 33, 10, 1).ToList();




            return PartialView();
        }
        public List<GetComicByChar_Result> getGenner(List<GetTheLoai_Result> lst2)
        {
            List<GetComicByChar_Result> lst = new List<GetComicByChar_Result>();

            foreach (var item in lst2)
            {
                GetComicByChar_Result obj = new GetComicByChar_Result
                {
                    Author = item.Author,
                    ChapterCount = item.ChapterCount,
                    CommentCount = item.CommentCount,
                    Content = item.Content,
                    Id = item.Id,
                    Images = item.Images,
                    Name = item.Name,
                    OtherName = item.OtherName,
                    rowcounts = item.rowcounts,
                    Slug = item.Slug,
                    Update = item.Update,
                    Views = item.Views
                };

                lst.Add(obj);
            }
            return lst;
        }
        protected override void Dispose(bool disposing)
        {
            db.Dispose();
            base.Dispose(disposing);
        }
    }
}
